package com.example.pets_java.service;

import com.example.pets_java.mapper.UserMapper;
import com.example.pets_java.pojo.User;
import com.example.pets_java.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public void register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
    }

    public Map<String, String> login(User user) {
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null && passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", existingUser.getUsername());
            claims.put("userId", existingUser.getId()); // Ensure to add userId
            String token = JwtUtils.generateJwt(claims);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            return response;
        }
        throw new RuntimeException("Invalid username or password");
    }

    public User findById(int id) {
        return userMapper.findById(id);
    }
}
